<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Border.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_Border extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Create a border round the image.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        if (isset($params['width'])) {
            $width = max(1, (int)$params['width']);
            $position = (isset($params['position']) && strtolower($params['position']) == 'inside' ? 'inside' : 'outside');
            $color = (isset($params['color']) ? $params['color'] : array(255, 255, 255));
            if (!is_array($color)) {
                $r = 0; $g = 0; $b = 0;
                if (preg_match('/#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i', $color, $match)) {
                    $r = $match[1];
                    $g = $match[2];
                    $b = $match[3];
                } else if (preg_match('/#?([0-9a-f])([0-9a-f])([0-9a-f])/i', $color, $match)) {
                    $r = $match[1] . $match[1];
                    $g = $match[2] . $match[2];
                    $b = $match[3] . $match[3];
                }
                $color = array(base_convert($r, 16, 10), base_convert($g, 16, 10), base_convert($b, 16, 10));
            }

            $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);

            $w = imagesx($image);
            $h = imagesy($image);
            if ($position != 'inside') {
                $target = imagecreatetruecolor($w+2*$width, $h+2*$width);
                imagecopy($target, $image, $width, $width, 0, 0, $w, $h);
                imagedestroy($image);
                $image = $target;
                $w += 2*$width;
                $h += 2*$width;
            }

            while($width--) {
                imagerectangle($image, $width, $width, $w-$width-1, $h-$width-1, $color);
            }

            imagecolordeallocate($image, $color);
            return true;
        }
        return false;
    }
}